<style lang="scss" scoped>
@import "@/assets/css/variable";
.manage {
  position: absolute;
  top: 0;
  bottom: $tabbar-height;
  width: 100%;
  background-color: $main-bgc;
  min-height: 100%;
  font-size: 1.2rem;
  overflow: auto;
  box-sizing: border-box;
  .list {
    padding-bottom: 1rem;
    .item {
      margin-top: 1rem;
      margin-left: 1rem;
      margin-right: 1rem;
      padding: 1rem;
      background-color: white;
      .flex1 {
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #999;
      }
      .flex2 {
        display: flex;
        .flex2-left {
          flex: 0 0 10rem;
          width: 10rem;
          height: 7.5rem;
          border-radius: 0.6rem;
          img {
            border-radius: 0.6rem;
            object-fit: cover;
          }
        }

        .flex2-right {
          .title {
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2; /* 设置行数 */
            -webkit-box-orient: vertical;
            color: $color-subtitle;
            line-height: 1.2em;
          }
          .desc {
            span {
              color: #999;
            }
          }
        }
      }
      .flex3 {
        display: flex;
        justify-content: flex-end;
        .btn {
          margin-left: 1rem;
        }
      }
    }
  }
}
.show {
  height: auto;
  background-color: white;
  position: relative;
  margin-bottom: 58px;
  .close-icon {
    position: absolute;
    width: 2.4rem;
    height: 2.4rem;
    right: 0.7rem;
    top: 0.7rem;
    border-radius: 1.2rem;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2;
  }
  .posterHtml {
    // display: flex;
    #coverImg {
      display: flex;
      width: 100%;
      max-height: 30rem;
      object-fit: cover;
    }
    .imgBox {
      width: 100%;
    }
    .content {
      padding: 1.2rem;
      display: flex;
      height: 14rem;
      justify-content: space-between;
      .desc {
        word-wrap: break-word;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        height: 100%;
        .line1 {
          font-size: 2rem;
          font-weight: bold;
          color: #333;
          display: flex;
          align-items: center;
        }
        .line2 {
          font-size: 2.2rem;
          font-weight: 900;
          color: #111;
          // overflow: hidden;
          // text-overflow: ellipsis;
          // display: -webkit-box;
          // -webkit-line-clamp:2; /* 设置行数 */
          // -webkit-box-orient:vertical;
        }
      }
    }
    .bottom-box {
      padding-bottom: 2rem;
      padding-left: 1.2rem;
      padding-right: 1.2rem;
    }
  }
}
.imgBox {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba($color: #000000, $alpha: 0.98);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 50px;
  z-index: 3000;
  img {
    width: 100%;
  }
  .tips {
    color: white;
  }
  .close-icon {
    position: fixed;
    width: 2.4rem;
    height: 2.4rem;
    right: 0.7rem;
    top: 0.7rem;
    border-radius: 1.2rem;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 3002;
  }
}
.fix-bottom {
  box-sizing: border-box;
  // padding-bottom: 2rem;
}
</style>
<template>
  <div class="manage">
    <!-- <my-activity-tabs></my-activity-tabs> -->
    <van-pull-refresh v-model="loadingRefresh" @refresh="refreshEvent">
      <van-tabs
        v-model="active"
        @click="onClickTabs"
        :color="$store.getters.getMasterColor || mainColor"
        sticky
      >
        <van-tab v-for="item in tabList" :key="item.id" :title="item.name">
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            offset="100"
            @load="getActivityPage"
          >
            <div class="list">
              <div class="item" v-for="item in list" :key="item.id">
                <div class="flex1">
                  <span>{{ item.createtime }}</span>
                  <span
                    :style="{ color: $store.getters.getMasterColor }"
                    v-if="item.status != 2"
                    >倒计时{{ item.leaveDay }}天</span
                  >
                  <span v-else>已结束</span>
                </div>
                <div class="flex2 margT-l">
                  <div class="flex2-left" @click="toShowView(item)">
                    <img :src="item.cover" />
                  </div>
                  <div class="flex2-right margL-l">
                    <div
                      class="title fs-14 t-bold"
                      :style="{ color: item.status == 2 ? '#999' : '#333' }"
                    >
                      {{ item.title }}
                    </div>
                    <div class="desc margT-l">
                      <span>浏览 {{ item.browse_num }}</span
                      ><span class="margL-l">参与 {{ item.join_num }}</span>
                    </div>
                  </div>
                </div>
                <div class="flex3">
                  <div class="btn">
                    <van-button
                      plain
                      type="default"
                      size="small"
                      @click="showPopBtn(item)"
                      >分享</van-button
                    >
                  </div>
                  <div class="btn">
                    <van-button
                      plain
                      :color="$store.getters.getMasterColor"
                      size="small"
                      @click="toApplyListView(item)"
                      >名单</van-button
                    >
                  </div>
                  <div class="btn">
                    <van-button
                      round
                      icon="ellipsis"
                      type="default"
                      size="small"
                      @click="showActionBtn(item)"
                    ></van-button>
                  </div>
                </div>
              </div>
              <!-- <div v-if="list.length > 0">
                  <div class="load-more color-l padding-all-m margB-l margT-l" v-if="finished==false" @click="getActivityPage">加载更多</div>
                  <div class="no-data color-l padding-all-m margT-l" v-else>已经到底了</div>
                </div> -->
            </div>
          </van-list>
        </van-tab>
      </van-tabs>
    </van-pull-refresh>
    <van-action-sheet
      v-model="showAction"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @select="onSelect"
    />

    <van-action-sheet
      v-model="groupShow"
      :actions="groups"
      cancel-text="取消"
      close-on-click-action
      @select="onGroup"
    />
    <van-popup v-model="showPop" position="bottom" round>
      <div class="show">
        <span
          class="close-icon"
          :style="{ backgroundColor: $store.getters.getMasterColor }"
          @click="showPop = false"
          ><van-icon color="white" name="cross"
        /></span>
        <!-- 海报html元素 -->
        <!-- <div id="posterHtml" :style="{backgroundImage: 'url('+thisItem.cover+')'}" v-show="false"> -->
        <div id="posterHtml" class="posterHtml">
          <img id="coverImg" :src="copyimg" />
          <!-- <div id="imgBox"></div> -->
          <div class="content">
            <div class="desc">
              <div class="line1">
                <span>快来参加</span>
                <van-icon class="margL-m" name="fire" color="red" />
              </div>
              <div class="line2">{{ thisItem.title }}</div>
            </div>
            <!-- 二维码 -->
            <!-- <div class="qrcode" id="qrcode" ref="qrcode"></div> -->
            <canvas class="qrcode" id="qrCode-canvas"></canvas>
          </div>
          <div class="margT-l bottom-box">
            <div class="fs-16 t-bold">{{ thisItem.merchantname }}</div>
            <div class="color-m margT-m">
              本次活动{{ thisItem.end_time }}结束
            </div>
          </div>
        </div>
        <div class="fix-bottom padding-lr">
          <van-button
            :color="$store.getters.getMasterColor"
            block
            @click="createPoster"
            :loading="createLoading"
            >生成海报</van-button
          >
        </div>
      </div>
    </van-popup>
    <div class="imgBox" v-if="showImgPop">
      <span
        class="close-icon"
        :style="{ backgroundColor: $store.getters.getMasterColor }"
        @click="
          showImgPop = false;
          showPop = false;
        "
        ><van-icon color="white" name="cross"
      /></span>
      <img :src="createImg" />
      <div class="tips margT-m fs-16">Tips:长按以上海报即可保存或转发</div>
    </div>
    <div class="tabbar-height"></div>
  </div>
</template>

<script>
// @ is an alias to /src
import {
  Tab,
  Tabs,
  List,
  PullRefresh,
  Loading,
  Button,
  ActionSheet,
  Toast,
  Popup,
  Icon,
  Dialog,
} from "vant";
// import myActivityTabs from "@/components/ActivityTabs.vue";
import QRCode from "qrcode";
import html2canvas from "html2canvas";
import { myMixins } from "@/assets/js/mixins.js";
export default {
  name: "Manage",
  mixins: [myMixins],
  components: {
    [PullRefresh.name]: PullRefresh,
    [List.name]: List,
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Loading.name]: Loading,
    [Button.name]: Button,
    [ActionSheet.name]: ActionSheet,
    [Popup.name]: Popup,
    [Icon.name]: Icon,
    [Dialog.name]: Dialog,
    // myActivityTabs
  },
  data() {
    return {
      createLoading: false,
      showImgPop: false,
      posterImg: "",
      code: "",
      showPop: false,
      showAction: false,
      actions: [
        { name: "编辑活动" },
        { name: "复制活动" },
        { name: "虚拟数据" },
        // { name: "开启活动" },
        { name: "结束活动" },
        { name: "删除活动" },
      ],
      groups: [
        { name: "拼团名单" },
        { name: "报名名单" },
      ],
      active: 0,
      loadingRefresh: false,
      mainColor: "#FF0000",
      tabList: [
        {
          id: 0,
          name: "全部",
        },
        {
          id: 1,
          name: "进行中",
        },
        {
          id: 2,
          name: "已结束",
        },
      ],
      list: [],
      loading: false,
      finished: false,
      pageNo: 1,
      pageSize: 8,
      id: "",
      thisItem: {},
      createImg: "",
      model: "",
      status: "",
      activityItem: "",
      copyimg: "",
      groupShow: false,
      separateDate: {}
      // activityItems: {}
    };
  },
  created() {
    const _this = this;
    const tabbar = JSON.parse(localStorage.getItem("tabbar"));
    document.title = tabbar[1].text;
  },
  mounted() {
    // document.title = '活动管理'
    if (process.env.NODE_ENV == "production") {
      //线上环境
      this.openid = localStorage.getItem("OPENID") || "没获取到";
    } else {
      this.openid = this.$store.state.openid || localStorage.getItem("OPENID");
    }
    if (
      this.openid == "undefined" ||
      !this.openid ||
      this.openid == undefined
    ) {
      window.location.href =
        location.href.indexOf("addons") > -1
          ? `${location.protocol}//${location.hostname}/addons/youmi_activitys/public/mobile/index.html#/case`
          : `${location.protocol}//${location.hostname}/mobile/index.html#/case`;
      return;
    }
    // this.configItemShare()
    this.getActivityPage();
  },
  methods: {
    getBase64Image(img) {
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
      var dataURL = canvas.toDataURL("image/" + ext);
      return dataURL;
    },
    //将图片对象转化为画布，返回画布
    ImageToCanvas(image) {
      var canvas = document.createElement("canvas");
      canvas.width = image.width;
      canvas.height = image.height;
      canvas.getContext("2d").drawImage(image, 0, 0); //0, 0参数画布上的坐标点，图片将会拷贝到这个地方
      document.getElementById("imgBox").appendChild(canvas);
      //return canvas;
    },
    createPoster() {
      // 生成海报
      const vm = this;
      vm.createLoading = true;
      const domObj = document.getElementById("posterHtml");
      html2canvas(domObj, {
        useCORS: true,
        allowTaint: true,
        logging: true,
        letterRendering: true,
        onclone(doc) {
          let e = doc.querySelector("#posterHtml");
          e.style.display = "block";
        },
      }).then(function (canvas) {
        // 在微信里,可长按保存或转发
        // let url = canvas.toDataURL('image/png')
        // const a = document.createElement('a'); // 创建a标签
        // a.setAttribute('download', `${new Date().getTime()}.png`);// download属性
        // a.setAttribute('href', url);// href链接
        // a.click();// 自执行点击事件
        let url = canvas.toDataURL("image/png");
        vm.createImg = url;
        vm.showImgPop = true;
        vm.createLoading = false;
      });
    },
    toShowView(item) {
      const _this = this;
      this.thisItem = item;
      // item.href||
      let href = `${location.protocol}//${location.hostname}${
        location.href.indexOf("addons") > -1
          ? "/addons/youmi_activitys/public"
          : ""
      }/plugin/index.html#/caseShow/${
        this.thisItem.model || "applyActivity"
      }/ActivityShow/${this.thisItem.id}?staff_id=${
        this.$store.state.staff_id
      }`;
      window.location.href = href;
    },
    createQrcode(item) {
      // item.href||
      let href = `${location.protocol}//${location.hostname}${
        location.href.indexOf("addons") > -1
          ? "/addons/youmi_activitys/public"
          : ""
      }/plugin/index.html#/caseShow/${
        this.thisItem.model || "applyActivity"
      }/ActivityShow/${this.thisItem.id}?staff_id=${
        this.$store.state.staff_id
      }`;
      console.log(href);
      let canvas = document.getElementById("qrCode-canvas");
      QRCode.toCanvas(canvas, href, (error) => {
        if (error) {
          //console.log(error)
        } else {
          canvas.style.width = "12rem";
          canvas.style.height = "12rem";
        }
      });
    },
    toApplyListView(item) {
      console.log(item);
      this.separateDate = item
      if(item.model == "groupBuying") return this.groupShow = true
      if(item.model == "voteplugin") {
        this.$store.commit("setActivityItem", item);
        return this.$router.push(`/manage/VotepluginList`);
      }
      this.$store.commit("setActivityItem", item);
      this.$router.push(`/manage/applyList`);
    },
    getActivityItem(item) {
      const _this = this;
      const toast = Toast.loading({
        forbidClick: true,
        message: "加载中...",
      });
      let params = {
        id: item.id,
        openid: _this.openid,
      };
      _this.$request.getActivityItem(params).then((res) => {
        //console.log(_this.activityItem, '_this.activityItem');
        _this.activityItem = res.data;
        toast.clear();
      });
    },
    showPopBtn(item) {
      if (item.status == 2) return this.$toast("本次活动已结束，无法分享");
      //console.log(item);
      let id = item.id;
      const _this = this;
      let params = {
        id: id,
      };
      _this.$request.getActivityItembase64(params).then((res) => {
        _this.copyimg = res.data;
      });
      this.showPop = true;
      this.thisItem = item;
      //console.log(this.thisItem,"thisItem")
      this.getActivityItem(item);
      _this.$nextTick(function () {
        _this.createQrcode(item);
      });

      // let img = document.getElementById('coverImg');
      // this.ImageToCanvas(img)
      // this.thisItem.cover = this.getBase64Image(img)
      // this.$forceUpdate()
    },
    showActionBtn(item) {
      // this.activityItems = item
      this.id = item.id;
      this.model = item.model;
      this.showAction = true;
    },
    onSelect(item) {
      // 默认情况下点击选项时不会自动收起
      // 可以通过 close-on-click-action 属性开启自动收起
      // this.show = false;
      //console.log(item.name);
      if (item.name == "编辑活动") {
        this.$router.push(`/case/${this.model}/${this.id}?is_edit=1`);
      } else if (item.name == "复制活动") {
        this.$router.push(`/case/${this.model}/${this.id}?is_edit=0`);
      } else if (item.name == "虚拟数据") {
        this.$router.push(`/fans/virtual/${this.id}`);
      } else if (item.name == "删除活动") {
        this.activityDel();
      } else if (item.name == "结束活动") {
        Dialog.confirm({
          title: "确定终止活动？",
          message: "指提前结束活动\n活动一旦终止，活动即结束",
        })
          .then(() => {
            // on confirm
          })
          .catch(() => {
            // on cancel
          });
        this.status = 1;
        this.activitySave(this.status);
      }
      //  else if (item.name == "开启活动") {
      //   this.status = 2;
      //   this.activitySave(this.status);
      // }
    },
    onGroup(item) {
      if (item.name == "拼团名单") {
        this.$store.commit("setActivityItem", this.separateDate);
        this.$router.push(`/manage/groupList`);
        // this.$router.push(`/case/${this.model}/${this.id}?is_edit=1`);
      } else if (item.name == "报名名单") {
        console.log(this.separateDate);
        this.$store.commit("setActivityItem", this.separateDate);
        this.$router.push(`/manage/applyList`);
      }
    },
    activitySave(status) {
      const _this = this;
      let params = {
        id: _this.id,
        status: status,
      };
      // params.cover = this.cover
      this.$request.activitySave(params).then((res) => {
        //console.log("res", res)
        if (res.ret == 200) {
          Toast("结束成功");
          _this.list = [];
          _this.pageNo = 1;
          _this.finished = false;
          _this.getActivityPage();
        }
      });
    },
    refreshEvent() {
      this.pageNo = 1;
      this.list = [];
      this.getActivityPage();
    },
    onLoad() {
      //console.log("onLoad")
    },
    activityDel() {
      const _this = this;
      let params = {
        id: this.id,
      };
      const toast = Toast.loading({
        forbidClick: true,
        message: "加载中...",
      });
      _this.$request
        .activityDel(params)
        .then((res) => {
          Toast("删除成功");
          _this.list = [];
          _this.pageNo = 1;
          _this.finished = false;
          _this.getActivityPage();
        })
        .finally(() => {
          toast.clear();
        });
    },
    getActivityPage() {
      const _this = this;
      let params = {
        //openid: _this.openid, // _this.$store.state.openid
        merchant_id: localStorage.getItem("merchant_id"),
		// merchant_id: 11111,
        status: _this.active ? _this.active : "",
        pageNo: _this.pageNo,
        pageSize: _this.pageSize,
      };
      this.loading = true;
      this.loadingRefresh = true;
      //console.log(params,"params")
      _this.$request
        .getActivityPage(params)
        .then((res) => {
          let data = res.data.data;
          //console.log(data, 'datadatadata');
          const list = data.map((item) => {
            const leaveTime =
              new Date(item.end_time).getTime() - new Date().getTime();
            const leaveDay = leaveTime / 1000 / 86400;
            item.leaveDay = Math.floor(leaveDay);
            return item;
          });
          _this.list.push(...list);
          //console.log(_this.list, '_this.list');

          if (_this.list.length >= res.data.totalCount) {
            _this.finished = true;
          } else {
            _this.pageNo++;
          }
          // this.$store.commit('setCaseList', this.caseList);
        })
        .finally(() => {
          //console.log('finally')
          this.loadingRefresh = false;
          this.loading = false;
        });
    },
    onClickTabs(index) {
      //console.log("onClickTabs123", index)
      this.active = index;
      this.list = [];
      this.pageNo = 1;
      this.finished = false;
      this.getActivityPage();
      if (index == 0) {
        //全部
        this.active = "";
      } else if (index == 1) {
        //进行中
      } else if (index == 2) {
        //已结束
      }
      // this.caseList = this.$store.getters.getCaseList
      // this.$emit("tabClick", index)
      // 请求接口获取对应的caseList
    },
  },
};
</script>
